// 项目库-项目列表

import React from 'react';
import { observer, useLocalStore } from 'mobx-react-lite';
import { Link } from 'react-router-dom';
import { Form, DatePicker, Button, Input, Card, Row, Col, Modal, Pagination, message } from 'antd';
import {
  SearchOutlined,
} from '@ant-design/icons';
import * as listApi from '~/apis/project/listApi';
import AjaxSelect from '~/components/AjaxSelect';
import { config } from '~/config/config';
import { getColumns } from './pageConfig';
import '~/styles/project.local.sass';

// 声明顶部SearchForm组件
const { RangePicker } = DatePicker;

const FormItem = Form.Item;

const showTotal = (total: number) => `Total: ${total}`;

const cardConfig = {
  size: 'small' as const,
  bordered: false,
};

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};


const ProjectList = observer(() => {
  const state = useLocalStore(() => ({
    loading: false,
    tableList: {
      data: [],
      pageNo: 1,
      pageSize: 8,
      totalCount: 0,
      totalPage: 0,
    },
    projectId: '',
    getData: {} as any,
    visibleFlag: false, // modal弹框显示标志
  }));

  const [form] = Form.useForm();
  const [modalForm] = Form.useForm(); // modal中的表单实例

  const doQuery = (curPage: number = 1) => {
    state.tableList.pageNo = curPage;

    const { pageNo, pageSize } = state.tableList;

    // 时间戳处理
    const { time } = state.getData;
    let startTime = null;
    let endTime = null;
    if (time && time.length > 0) {
      startTime = new Date(time[0]).getTime();
      endTime = new Date(time[1]).getTime();
    }

    const params = {
      pageNum: pageNo,
      pageSize,
      startTime,
      endTime,
      ...state.getData,
    };

    delete params.time;

    state.loading = true;

    listApi.getProjectList(params).then((res) => {
      state.tableList = {
        ...state.tableList,
        data: res.data,
        totalCount: res.pageInfo ? res.pageInfo.total : 0,
        totalPage: res.pageInfo ? res.pageInfo.totalPages : 0,
      };
    }).finally(() => {
      state.loading = false;
    });
  };

  const onSearch = (values: any) => {
    state.getData = values;

    doQuery(1);
  };

  const onReset = () => {
    form.resetFields();
  };

  const columns = getColumns(ProjectList);

  const {
    loading, tableList: {
      pageNo, totalCount, pageSize, data,
    },
  } = state;

  const tableOption: any = {
    loading,
    columns,
    pagination: {
      current: pageNo,
      total: totalCount,
      pageSize,
      size: 'small',
      showQuickJumper: true,
      showTotal,
      onChange: (curPage: number) => {
        doQuery(curPage);
      },
    },
    dataSource: data || [],
    rowKey: 'id',
    size: 'small',
    // bordered: true,
  };

  // 关闭弹框
  const handleAuditCancel = () => {
    state.visibleFlag = false;
  };

  // 弹出modal框
  const handleConsult = (id: string) => {
    state.visibleFlag = true;
    state.projectId = id;
    modalForm.resetFields(); // 清空modal弹框值
  };

  // consult确认
  const handleConsultConfirm = (values: any) => {
    state.visibleFlag = false;
    listApi.handleProjectConsult(values).then(() => {
      message.success('consult success');
      doQuery(1);
    });
  };

  // 获取表单数据
  const onOk = () => {
    modalForm.validateFields().then((values) => {
      values.projectId = state.projectId;
      handleConsultConfirm(values);
    });
  };

  // Modal属性
  const modalOption: any = {
    title: 'Consult ',
    visible: state.visibleFlag,
    width: 700,
    forceRender: true, // 强制渲染
    onOk,
    onCancel: handleAuditCancel,
  };

  // 关注
  const handleStar = (id: string) => {
    listApi.handleStar(id).then(() => {
      message.success('success');
      doQuery(1);
    });
  };

  // 取消关注
  const handleCancelStar = (id: string) => {
    listApi.handleCancelStar(id).then(() => {
      message.success('success');
      doQuery(1);
    });
  };

  React.useEffect(() => {
    doQuery(1);
  }, []);


  const timestampToTime = (timestamp: any) => {
    const date = new Date(timestamp);// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
    const Y = `${date.getFullYear()}/`;
    const M = `${date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1}/`;
    const D = `${date.getDate()} `;
    return Y + M + D;
  };

  // 项目列表渲染
  const imgUrl = config.ossUrl;
  const projectList = tableOption.dataSource;
  const projectListItems: any = [];
  projectList.forEach((item: any) => {
    projectListItems.push(
      <li key={item.id}>
        <Link to={`/project/details?id=${item.id as string}`}>
          <div className="list-container">
            <span className="avatar">
              {
                (() => {
                  if (item.thumbnail) {
                    return (<img src={`${imgUrl}${item.thumbnail as string}`} alt='' className="avatar-img"/>);
                  }
                  return <></>;
                })()
              }
            </span>
            <div className="project-content">
              <div className="project-title">
                <span></span>
                <b>{item.projectTitle}</b>
              </div>
              <div className="project-detail">
                <p>Country/Region: <em>{item.countryName}</em></p>
                <p>Investment: <em>{item.totalAmount}</em></p>
                <p>Project stage: <em>{item.stageName}</em></p>
                <p>Publish time: <em>{timestampToTime(item.startingTime)}</em></p>
              </div>
            </div>
          </div>
        </Link>

        <div className="bottom-tag">
          <button><Link to={`/project/details?id=${item.id as string}`}>View</Link></button>
          <button onClick={() => handleConsult(item.id)}>Consult</button>
          <button className={item.star ? 'disabled' : ''}
            onClick={item.star ? () => handleCancelStar(item.id) : () => handleStar(item.id)}> {item.star ? 'Stared' : 'Star'}</button>
        </div>
      </li>,
    );
  });

  return (
    <div>
      {/* 顶部搜索栏 */}
      <div className="project-search">
        <Card {...cardConfig} className="search-card">
          <Form form={form} onFinish={onSearch}>
            <Row>
              <Col span={4}>
                <Form.Item name="time" {...formItemLayout}>
                  <RangePicker
                    format="YYYY-MM-DD"
                    placeholder={['Start Time', 'End Time']}
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
              <Col span={4}>
                <Form.Item name="countryId" shouldUpdate={true} {...formItemLayout}
                >
                  <AjaxSelect
                    placeholder="Country/Region"
                    type="countryList"
                  />
                </Form.Item>
              </Col>
              <Col span={4}>
                <FormItem name="industryId" {...formItemLayout}
                >
                  <AjaxSelect
                    placeholder="Industry"
                    type="industryList"
                  />
                </FormItem>
              </Col>

              <Col span={4}>
                <Form.Item name="stageCode" {...formItemLayout} >
                  <AjaxSelect
                    placeholder="Project stage"
                    type="projectStage"
                  />
                </Form.Item>
              </Col>
              <Col span={4}>
                <FormItem name="projectName" {...formItemLayout} >
                  <Input
                    allowClear={true}
                    onPressEnter={onSearch}
                    prefix={
                      <SearchOutlined style={{ color: '#A9B8CF' }}/>
                    }
                  />
                </FormItem>
              </Col>
              <Col span={2}>
                <FormItem {...formItemLayout}>
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="mr-2"
                    block
                  >
                    Search
                  </Button>
                </FormItem>
              </Col>
              <Col span={2}>
                <FormItem {...formItemLayout}>
                  <Button className="mr-2" onClick={onReset} block>
                    Reset
                  </Button>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Card>
      </div>

      <div className="project-list">
        <ul>
          {projectListItems}
        </ul>
      </div>

      <div>
        <Pagination
          showQuickJumper
          defaultCurrent={1}
          total={tableOption.pagination.total}
          showTotal={(total) => `Total ${total}`}
          pageSize={8}
          onChange={tableOption.pagination.onChange}/>
      </div>


      <div>
        <Modal
          {...modalOption}
        >
          <Form
            {...formItemLayout}
            form={modalForm}
          >
            <Form.Item name="subject">
              <Input placeholder="Title" className="mb-4"/>
            </Form.Item>
            <Form.Item name="content">
              <Input.TextArea placeholder="Content" rows={6}/>
            </Form.Item>
          </Form>
        </Modal>

      </div>
    </div>
  );
});


export default ProjectList;
